/*
 * @Author: caorui 778943319@qq.com
 * @Date: 2025-07-22 15:56:21
 * @LastEditors: caorui 778943319@qq.com
 * @LastEditTime: 2025-07-22 16:20:30
 * @FilePath: \notes\deploy.js
 * @Description:
 *
 */
const { execSync } = require("child_process");
const fs = require("fs");
const path = require("path");

// 配置目标仓库 - 已修正为 GitHub 仓库
const TARGET_REPO = "https://github.com/crui14994/myNotes.git"; // 确保这是 GitHub 地址
const TARGET_BRANCH = "master";
const TARGET_DIR = path.resolve(__dirname, "deploy-repo");
const DIST_DIR = path.resolve(__dirname, ".vitepress", "dist");
const COMMIT_MESSAGE = `Deploy: ${new Date().toISOString()}`;

// 增加重试机制的函数
function executeWithRetry(command, options, maxRetries = 3, delay = 2000) {
  let retries = 0;
  while (retries < maxRetries) {
    try {
      execSync(command, options);
      return true;
    } catch (error) {
      console.error(`⚠️ 尝试 ${retries + 1}/${maxRetries} 失败: ${error.message}`);
      retries++;
      if (retries < maxRetries) {
        console.log(`⏳ ${delay / 1000}秒后重试...`);
        new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
  throw new Error(`操作失败: ${command}`);
}

// 清空目标目录（保留.git）
function cleanTargetDir() {
  if (!fs.existsSync(TARGET_DIR)) return;

  fs.readdirSync(TARGET_DIR).forEach((file) => {
    if (file === ".git") return;

    const filePath = path.join(TARGET_DIR, file);
    if (fs.lstatSync(filePath).isDirectory()) {
      fs.rmSync(filePath, { recursive: true, force: true });
    } else {
      fs.unlinkSync(filePath);
    }
  });
}

// 复制dist内容到目标目录
function copyDistToTarget() {
  fs.cpSync(DIST_DIR, TARGET_DIR, {
    recursive: true,
    force: true,
  });
}

// 执行Git操作
function gitOperations() {
  // 确保在master分支
  executeWithRetry(`git checkout ${TARGET_BRANCH}`, { cwd: TARGET_DIR, stdio: "inherit" });

  executeWithRetry("git add .", { cwd: TARGET_DIR, stdio: "inherit" });
  executeWithRetry(`git commit -m "${COMMIT_MESSAGE}"`, { cwd: TARGET_DIR, stdio: "inherit" });
  executeWithRetry(`git push origin ${TARGET_BRANCH}`, { cwd: TARGET_DIR, stdio: "inherit" });
}
// 主函数
function main() {
  try {
    // 初始化目标仓库（如果不存在）
    if (!fs.existsSync(TARGET_DIR)) {
      fs.mkdirSync(TARGET_DIR, { recursive: true });

      // 使用带重试机制的克隆命令
      console.log("🔄 正在克隆目标仓库...");
      executeWithRetry(`git clone -b ${TARGET_BRANCH} ${TARGET_REPO} ${TARGET_DIR}`, {
        stdio: "inherit",
        env: {
          ...process.env,
          GIT_HTTP_BUFFER: "524288000",
        },
      });
    } else {
      // 确保目标仓库的远程地址是正确的
      const currentRemote = execSync("git remote get-url origin", {
        cwd: TARGET_DIR,
        encoding: "utf-8",
      }).trim();

      if (currentRemote !== TARGET_REPO) {
        console.log("⚠️ 检测到仓库远程地址不匹配，正在修正...");
        console.log(`当前地址: ${currentRemote}`);
        console.log(`目标地址: ${TARGET_REPO}`);

        // 移除现有远程并添加正确的远程
        executeWithRetry("git remote remove origin", { cwd: TARGET_DIR });
        executeWithRetry(`git remote add origin ${TARGET_REPO}`, { cwd: TARGET_DIR });
        console.log("✅ 已更新远程地址");
      }
    }

    // 更新目标仓库（从master分支拉取）
    console.log("🔄 正在更新目标仓库...");
    executeWithRetry(`git pull origin ${TARGET_BRANCH}`, { 
      cwd: TARGET_DIR, 
      stdio: "inherit",
      env: {
        ...process.env,
        GIT_HTTP_BUFFER: "524288000",
      }
    });
    
    // 清理目标目录
    console.log("🧹 清理目标目录...");
    cleanTargetDir();
    
    // 复制dist内容到目标目录
    console.log("📂 复制构建文件...");
    copyDistToTarget();
    
    // 执行Git操作（提交并推送）
    console.log("📝 提交更改...");
    gitOperations();
    
    console.log("✅ 成功部署到目标仓库的master分支");
  } catch (error) {
    console.error("❌ 部署失败:", error.message);
    console.log("💡 解决方案建议:");
    console.log("1. 检查网络连接是否稳定");
    console.log("2. 尝试增加Git缓冲区大小: git config --global http.postBuffer 524288000");
    console.log("3. 尝试使用SSH方式克隆仓库（需要配置SSH密钥）");
    process.exit(1);
  }
}

main();
